use play_api::*;
use play_auth_offline::OfflinePlayer;
use play_back::BackEndSever;
use play_back::ntex;
use play_db::DB;
use play_down::Aria2Downloader;
use play_fs::FileChecker;
use play_meta::MinecraftDownloader;
use std::sync::Arc;
use tokio::signal;

#[ntex::main]
async fn main() -> std::io::Result<()> {
    let mut downloader = Aria2Downloader::new("http://127.0.0.1:5600/jsonrpc", "token");
    println!("Starting aria2");
    let mut task0 = downloader.init()?;
    let database = DB::new("paly.db");
    if let Err(e) = database.init() {
        eprintln!("Error initializing database: {}", e);
    }
    let auth = OfflinePlayer;
    let filesystem = FileChecker;
    let versiongetter = MinecraftDownloader;
    let server = Arc::new(BackEndSever::new(
        downloader,
        database,
        auth,
        filesystem,
        versiongetter,
    ));
    let task1 = server.start([127, 0, 0, 1], 8080).await?;
    println!("Server started");
    signal::ctrl_c().await?;
    println!("Server stopping");
    task0.kill().await?;
    println!("Aria2 stopped");
    task1.stop(true).await;
    println!("Server stopped");
    Ok(())
}
